import { get as _get } from 'lodash';
import { Observable, isObservable } from 'rxjs';
import { take } from 'rxjs/operators';

export function result(data: { [key: string]: any }, pathFn: any): any {
  if (!pathFn) {
    return data;
  } else if (typeof pathFn === 'string') {
    return _get(data, pathFn);
  } else if (typeof pathFn === 'function') {
    return pathFn(data);
  }
  return undefined;
}

/**
 * 提供类型不确定性函数的返回值统一处理的方法
 * @param call 返回值为 boolean 类型的可执行函数、Promise、Observable
 * @param callback 回调函数
 */
export function doFnResult(call: any, callback?): void {
  if (call instanceof Promise) {
    call
      .then((res): void => {
        if (res !== false) {
          runCallback(callback, true);
        } else {
          runCallback(callback, false);
        }
      })
      .catch((): void => {
        runCallback(callback, false);
      });
  } else if (isObservable(call)) {
    (call as Observable<boolean | void | object>).pipe(take(1)).subscribe(
      (res): void => {
        if (res !== false) {
          runCallback(callback, true);
        } else {
          runCallback(callback, false);
        }
      },
      (): void => {
        runCallback(callback, false);
      },
    );
  } else if (call || undefined === call) {
    runCallback(callback, true);
  } else {
    runCallback(callback, false);
  }

  function runCallback(cb, flag): void {
    if (cb) {
      cb(flag);
    }
  }
}
